package net.huashitong.user.web;

import java.util.*;

import net.huashitong.Indicators.databean.IndicatorBreakdownDatabean;
import net.huashitong.Indicators.entity.IndicatorBreakdown;
import net.huashitong.Indicators.filter.IndicatorBreakdownFilter;
import net.huashitong.Indicators.service.EarlyWarningService;
import net.huashitong.Indicators.service.IndicatorBreakdownService;
import net.huashitong.Indicators.utils.DataUtils;
import net.huashitong.Indicators.utils.DateForIndUtils;
import net.huashitong.Indicators.utils.IndustryNameUtils;
import net.huashitong.user.entity.SecurityToken;
import net.huashitong.user.filter.LoginFilter;
import net.huashitong.user.service.UserService;
import net.huashitong.user.utils.RegularExpressionsUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.StringUtils;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;

/**
 * 用户模块接口
 *
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.09.04
 */
@Controller
@RequestMapping("/api/user/")
public class UserController extends JsonBaseController {

    private UserService userService;
    
    private SysUserService sysUserService;
    private final static String apiKey= "b3232c91e3336d52ae80b73bb0a1cb91";
	@Autowired
	private IndicatorBreakdownService breakdownService;
    
    @Autowired
    public UserController(UserService userService,SysUserService sysUserService) {
        this.userService = userService;
        this.sysUserService = sysUserService;
    }

    @Autowired
    private EarlyWarningService earlyWarningService;
    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 登录
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Message login(@RequestBody LoginFilter filter) {
		Map<String, Object> map = new HashMap<String, Object>();
    	if("18606951877".equals(filter.getMobile())&&"1234".equals(filter.getValidCode()))
		{
			SecurityToken securityToken = new SecurityToken();
			//securityToken.setUserId(sysLogin==null?filter.getMobile():sysLogin.getSysId());
			//securityToken.setToken(getToken());
			map.put("userId",filter.getMobile());
			map.put("token", UUID.randomUUID().toString().replace("-", ""));
			return coverMessage("200", "获取成功", map);
		} else {
			try {
				//短信验证码校验
				SecurityToken token = userService.saveLogin(filter);

				map.put("userId", token.getUserId());
				map.put("token", token.getToken());
				map.put("timestamp", Long.toString(System.currentTimeMillis()));
				return coverMessage("200", "获取成功", map);
			} catch (Exception e) {
				return coverMessage("500","失败",e.getMessage());
			}
		}


    }
    /**
     * 发送验证码
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendValidCode")
    public Message sendValidCode(@RequestBody LoginFilter filter){
    	if (StringUtils.isBlank(filter.getMobile())
				|| !RegularExpressionsUtils.phone(filter.getMobile())) {
			return coverMessage("500", "参数有误，请重新输入");
		}
		if (!userService.queryByMobile(filter.getMobile())) {
			return coverMessage("500", "用户不存在");
		}
		String validCode = Integer.toString((int)((Math.random()*9+1)*1000));
    	YunpianClient clnt = new YunpianClient(apiKey).init();
    	//修改账户信息API
    	Map<String, String> param = clnt.newParam(2);
    	param.put(YunpianClient.MOBILE, filter.getMobile());
    	param.put(YunpianClient.TEXT, "【经济指标管理系统】您的验证码是"+validCode+"。如非本人操作，请忽略本短信");
    	Result<SmsSingleSend> r = clnt.sms().single_send(param);
    	//获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
    	//账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
    	//最后释放client
    	clnt.close();
    	userService.saveValid(filter.getMobile(),validCode);
    	if(r.getCode()!=0){
    		return coverMessage("500", "短信验证码获取失败");
    	}
		return coverMessage("200", "短信验证码发送成功");
    }
    /**
     * 获取用户信息
     * @param bean
     * @return
     */
    @ResponseBody
    @RequestMapping("/userInfo")
    public Message userInfo(@RequestBody SysUserDataBean bean){

    	if("18606951877".equals(bean.getUserId()))
		{
			bean.setName("林工");
			return coverMessage("200", "获取成功", bean);
		}
		SysUser sysUser = sysUserService.getById(bean.getUserId());
		bean.setPosition(sysUser.getPosition());
		bean.setName(sysUser.getName());
		return coverMessage("200", "获取成功", bean);
    }
    /**
     * 查询重点指标和预警指标
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryImportantAndWarning")
    public Message queryImportantAndWarning(@RequestBody IndicatorBreakdownFilter filter){
    	List<Map<String, Object>> earlyWarnings = earlyWarningService.queryByCreate();
    	Map<String, Object> map = new HashMap<String, Object>();
//    	map.put("earlyWarnings", earlyWarnings);
    	List<String> ids = new ArrayList<String>();
    	ids.add(IndustryNameUtils.SolidIndexId);
    	ids.add(IndustryNameUtils.PublicIndexId);
    	ids.add(IndustryNameUtils.GDPIndexId);
    	List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
    	for (String id : ids) {
    		Map<String, Object> mapSec = new HashMap<String, Object>();
			filter.setIndustryId(id);
			String jud = DataUtils.getValue(filter);
			String date = DataUtils.getValueMonth(jud,filter);
			date = DateForIndUtils.getMonth(date);
			IndicatorBreakdown indicatorBreakdown = new IndicatorBreakdown();
			indicatorBreakdown.setIndustryId(id);
			indicatorBreakdown.setArea(filter.getArea());
			indicatorBreakdown.setDate(date);
			filter = IndustryNameUtils.changeName(filter);
			List breakdown = breakdownService.queryAll(indicatorBreakdown.getDate(),filter.getIndustryName(),indicatorBreakdown.getArea());
			List breakdown2 = breakdownService.queryAllSec(indicatorBreakdown.getDate(),filter.getIndustryName(),indicatorBreakdown.getArea());
			//System.out.println(breakdown.get(0));
			Object[] object = (Object[]) breakdown.get(0);
			Object[] objectSec = (Object[]) breakdown2.get(0);
			mapSec.put("industryId", object[0]);
			mapSec.put("industryName", object[2]);
			mapSec.put("rankRatio", object[4].toString());
			mapSec.put("rankCumulative", objectSec[4].toString());
			list.add(mapSec);
		}
    	list.addAll(earlyWarnings);
//    	map.put("important", list);
		return coverMessage("200", "数据获取成功", list);
    }
}
